﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.Configuration;
using Phoenix.ReflectionExtensions;
using PServiceBus.Core.Runtime;
using PServiceBus.Core.Logger;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Configuration;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Core.Manager {
    public class TopicMessageInspectorManager {
        static List<ITopicMessageInspector> _inspectors;
        private static List<ITopicMessageInspector> Inspectors {
            get {
                if (_inspectors == null) {
                    _inspectors = new List<ITopicMessageInspector>();
                    foreach (var inspector in ConfigurationProvider.TopicMessageInspectorConfigs) {
                        var ex = MethodHelper.Try(() =>
                        {
                            var msgInspector = DynamicBroker.Broker[inspector.Type].New() as ITopicMessageInspector;
                            _inspectors.Add(msgInspector);
                        });
                        ESBLogger.Log(ex);
                    }
                }
                return _inspectors;
            }
        }

        /// <summary>
        /// Validate the content of the message
        /// </summary>
        /// <param name="message"></param>
        public static bool Inspect(TopicMessage message) {
            foreach (var inspector in Inspectors)
                if (!inspector.Verify(message))
                    return false;
            return true;
        }
    }
}
